﻿#include "ssWXPicture.h"

#ifdef SS_USE_WXWIDGETS
namespace StarSeeker
{

ssWXPicture::ssWXPicture()
{
}

ssWXPicture::~ssWXPicture()
{
	SS_SAFE_DEL_ARRAY(m_pBit)
}

bool ssWXPicture::LoadFromFile(const char* path)
{
	if (!m_pBit)
	{
		wxImage::AddHandler(new wxTGAHandler);
		wxImage img(wxString(path, wxConvLocal), wxBITMAP_TYPE_TGA);
		if (img.Ok())
		{
			m_width = img.GetWidth();
			m_height = img.GetHeight();
			u8 *bitmapData = img.GetData();
			u8 *alphaData = img.GetAlpha();
			i32 bytesPerPixel = 3;
			if (img.HasAlpha())
			{
				bytesPerPixel = 4;
				m_glImageFormat = GL_RGBA;
				m_glInternalFormat = GL_RGBA;
			}
			else
			{
				m_glImageFormat = GL_RGB;
				m_glInternalFormat = GL_RGBA;
			}
			i32 imageSize = m_width * m_height * bytesPerPixel;
			SS_SAFE_NEW_ARRAY(m_pBit, u8, imageSize)
			i32 rev_val = m_height - 1;
			for(i32 y=0; y<m_height; y++)
			{
				for(i32 x=0; x<m_width; x++)
				{
					m_pBit[(x+y*m_width)*bytesPerPixel] = bitmapData[( x+(rev_val-y)*m_width)*3];
					m_pBit[(x+y*m_width)*bytesPerPixel+1] = bitmapData[( x+(rev_val-y)*m_width)*3 + 1];
					m_pBit[(x+y*m_width)*bytesPerPixel+2] = bitmapData[( x+(rev_val-y)*m_width)*3 + 2];
					if(bytesPerPixel==4)
						m_pBit[(x+y*m_width)*bytesPerPixel+3]= alphaData[ x+(rev_val-y)*m_width ];
				}
			}
			img.Destroy();
			return true;
		}
	}
	return false;
}

}
#endif
